package com.example.demo.security.jwt;

import com.example.demo.entity.User;
import com.example.demo.service.JwtUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JwtTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUserDetailService jwtUserDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtProperties jwtProperties;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        logger.info(request.getMethod());

        if(request.getMethod().equals("OPTIONS")){
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(jwtProperties.getHeader());

        try{
           System.out.println("filter:  token:  "+token);
            if (token != null && jwtTokenUtil.getUseridFromToken(token)!= null && SecurityContextHolder.getContext().getAuthentication() == null){
                String id = jwtTokenUtil.getUseridFromToken(token);
                logger.info("checking authentication: " + id);
                User user = (User) jwtUserDetailsService.loadUserByUsername(id);
                System.out.println("user:   "+user.getToken());
                if (jwtTokenUtil.validateToken(token, user)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //设置用户登录状态
                    logger.info("authenticated user: " + id + ", setting security context");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
                else{
                    throw new RuntimeException("用户尚未登录");
                }
            }
            else{
                throw new RuntimeException("用户尚未登录");
            }
        }catch (Exception e){
            logger.warn(e.getLocalizedMessage());
        }

        filterChain.doFilter(request, response);

    }


}

